<template>
  <div class="device-list-container">
    <!-- 搜索表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.eqname" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-input v-model="searchForm.eqtype" placeholder="请输入设备类型" clearable />
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.eqstatus" placeholder="请选择" clearable>
            <el-option label="正常运行" :value="0" />
            <el-option label="异常" :value="1" />
            <el-option label="停机维护" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model.number="searchForm.eqmodel" placeholder="请输入设备型号" type="text" clearable />
        </el-form-item>
        <el-form-item label="制造商">
          <el-input v-model="searchForm.eqmanufacture" placeholder="请输入制造商" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备列表 -->
    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <el-button type="primary" @click="handleAddDevice">新增设备</el-button>
        <el-button
          type="danger"
          :disabled="selectedDevices.length === 0 || formSubmitting"
          @click="handleBatchDelete"
          :loading="formSubmitting"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        :data="deviceList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="eqid" label="设备ID" width="90" />
        <el-table-column prop="eqname" label="设备名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="eqtype" label="设备类型" width="120" />
        <el-table-column prop="eqstatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.eqstatus)">{{ getDeviceStatusLabel(row.eqstatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="eqmodel" label="型号" width="90" />
        <el-table-column prop="eqmanufacture" label="制造商" width="140" />
        <el-table-column prop="eqtime" label="购买日期" width="160">
            <template #default="{ row }">
                {{ row.eqtime ? row.eqtime.split('T')[0] : 'N/A' }}
            </template>
        </el-table-column>
        <el-table-column prop="eqcount" label="数量" width="80" />
        <el-table-column prop="eqprice" label="价格(元)" width="100" />
        <el-table-column prop="eqv" label="电压(V)" width="90" />
        <el-table-column prop="eqa" label="电流(A)" width="90" />
        <el-table-column prop="eqw" label="功率(W)" width="100" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">查看</el-button>
            <el-button type="warning" link @click="handleEditDevice(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDeleteDevice(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="false"
        :disabled="loading || formSubmitting"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑设备弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑设备' : '新增设备'"
      width="600px"
      :before-close="handleCloseDialog"
      destroy-on-close
    >
      <el-form
        :model="deviceForm"
        :rules="deviceFormRules"
        ref="deviceFormRef"
        label-width="120px"
      >
        <el-form-item label="设备名称" prop="eqname">
          <el-input v-model="deviceForm.eqname" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="设备类型" prop="eqtype">
          <el-input v-model="deviceForm.eqtype" placeholder="请输入设备类型" clearable />
        </el-form-item>
        <el-form-item label="设备状态" prop="eqstatus">
          <el-select v-model="deviceForm.eqstatus" placeholder="请选择设备状态" style="width: 100%;">
            <el-option label="正常运行" :value="0" />
            <el-option label="异常" :value="1" />
            <el-option label="停机维护" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="eqmodel">
          <el-input v-model.number="deviceForm.eqmodel" placeholder="请输入设备型号" type="text" />
        </el-form-item>
        <el-form-item label="制造商" prop="eqmanufacture">
          <el-input v-model="deviceForm.eqmanufacture" placeholder="请输入制造商" />
        </el-form-item>
        <el-form-item label="购买日期" prop="eqtime">
          <el-date-picker
            v-model="deviceForm.eqtime"
            type="date"
            placeholder="选择购买日期"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="数量" prop="eqcount">
          <el-input-number v-model="deviceForm.eqcount" :min="1" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="eqprice">
          <el-input-number v-model="deviceForm.eqprice" :min="0" :precision="2" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="电压(V)" prop="eqv">
          <el-input-number v-model="deviceForm.eqv" :min="0" :precision="2" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="电流(A)" prop="eqa">
          <el-input-number v-model="deviceForm.eqa" :min="0" :precision="2" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="功率(W)" prop="eqw">
          <el-input-number v-model="deviceForm.eqw" :min="0" :precision="2" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="设备描述" prop="eqdiscribe">
          <el-input
            v-model="deviceForm.eqdiscribe"
            type="textarea"
            :rows="3"
            placeholder="请输入设备描述 (最多200字)"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog" :disabled="formSubmitting">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm" :loading="formSubmitting">
            {{ isEdit ? '更新' : '新增' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useDeviceStore } from '@/stores/modules/device';
import { storeToRefs } from 'pinia';

const deviceStore = useDeviceStore();

const {
  deviceList,
  loading,
  total,
  searchForm, 
  selectedDevices,
  deviceForm,
  isEdit,
  dialogVisible,
  formSubmitting // 引入 formSubmitting
} = storeToRefs(deviceStore);

const deviceFormRef = ref(null);

const getStatusTagType = (status) => {
  return deviceStore.getStatusTagType(status);
};
const getDeviceStatusLabel = (status) => {
  return deviceStore.getDeviceStatusLabel(status);
};


const deviceFormRules = reactive({ /* ... 规则保持不变 ... */
  // 规则保持不变，这里省略以保持代码简洁，请使用您之前正确的规则
  eqname: [
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { type: 'string', transform: (value) => value === '' ? null : value, trigger: 'blur' },
  ],
  eqtype: [
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    { type: 'string', transform: (value) => value === '' ? null : value, trigger: 'blur' },
  ],
  eqstatus: [
    { type: 'number', message: '设备状态必须为数字', trigger: 'change', transform: (value) => {
        if (value === '') return null; 
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
  ],
  eqmodel: [
    { type: 'number', message: '型号必须为数字', trigger: 'blur', transform: (value) => {
        if (value === '') return null;
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
  ],
  eqmanufacture: [
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { type: 'string', transform: (value) => value === '' ? null : value, trigger: 'blur' },
  ],
  eqtime: [
    { type: 'string', transform: (value) => value === '' ? null : value, trigger: 'change' },
  ],
  eqcount: [
    { type: 'number', message: '数量必须为数字', trigger: 'blur', transform: (value) => {
        if (value === '') return null;
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
    { min: 1, message: '数量不能小于1', trigger: 'blur', type: 'number' },
  ],
  eqprice: [
    { type: 'number', message: '价格必须为数字', trigger: 'blur', transform: (value) => {
        if (value === '') return null;
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
    { min: 0, message: '价格不能小于0', trigger: 'blur', type: 'number' },
  ],
  eqv: [
    { type: 'number', message: '电压必须为数字', trigger: 'blur', transform: (value) => {
        if (value === '') return null;
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
    { min: 0, message: '电压不能小于0', trigger: 'blur', type: 'number' },
  ],
  eqa: [
    { type: 'number', message: '电流必须为数字', trigger: 'blur', transform: (value) => {
        if (value === '') return null;
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
    { min: 0, message: '电流不能小于0', trigger: 'blur', type: 'number' },
  ],
  eqw: [
    { type: 'number', message: '功率必须为数字', trigger: 'blur', transform: (value) => {
        if (value === '') return null;
        const num = Number(value);
        return isNaN(num) ? null : num;
      }
    },
    { min: 0, message: '功率不能小于0', trigger: 'blur', type: 'number' },
  ],
  eqdiscribe: [
    { max: 200, message: '设备描述不能超过200字', trigger: 'blur' },
    { type: 'string', transform: (value) => value === '' ? null : value, trigger: 'blur' },
  ],
});


const handleSearch = async () => {
  deviceStore.searchForm.pageNo = 1;
  await deviceStore.fetchDeviceList();
};

const handleResetSearch = async () => {
  await deviceStore.resetSearchForm();
};

const handleAddDevice = () => {
  deviceStore.resetDeviceForm();
  deviceStore.isEdit = false;
  deviceStore.dialogVisible = true;
  setTimeout(() => {
    if (deviceFormRef.value) {
      deviceFormRef.value.clearValidate();
    }
  }, 0);
};

const handleEditDevice = (row) => {
  deviceStore.deviceForm = {
    ...row,
    eqtime: row.eqtime && typeof row.eqtime === 'string' && row.eqtime.includes('T')
             ? row.eqtime.split('T')[0]
             : row.eqtime || '',
  };
  deviceStore.isEdit = true;
  deviceStore.dialogVisible = true;
  setTimeout(() => {
    if (deviceFormRef.value) {
      deviceFormRef.value.clearValidate();
    }
  }, 0);
};

const handleDeleteDevice = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除设备“${row.eqname || row.eqid}”吗？此操作不可逆！`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    // 这里调用 store 中单个删除方法，它会处理成功/失败提示和列表刷新
    await deviceStore.deleteDevice(row.eqid);
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除操作'); // 只有用户取消才在这里提示
    } else {
      // 实际的错误会在 store 内部的 deleteDevice 中弹出 ElMessage，这里可以不重复弹窗
      console.error('删除设备操作在组件层捕获到错误（可能已在store中提示）:', error);
    }
  }
};

const handleBatchDelete = async () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请至少选择一个要删除的设备');
    return;
  }
  try {
    const confirmMessage = `确认删除选中的 ${selectedDevices.value.length} 个设备吗？此操作不可逆！`;
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const deviceIds = selectedDevices.value.map((device) => device.eqid);
    // 调用 store 的批量删除方法，它会负责所有并行请求、结果统计和提示
    await deviceStore.deleteDevices(deviceIds); 
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消批量删除操作');
    } else {
      // 这里的错误通常是 Promise.allSettled 外部的，或者已经由 store 内部处理
      console.error('批量删除操作在组件层捕获到错误（可能已在store中提示）:', error);
    }
  }
};

const handleSubmitForm = async () => {
  try {
    await deviceFormRef.value.validate(); 
    deviceStore.formSubmitting = true;

    if (isEdit.value) {
      await deviceStore.updateDevice(deviceStore.deviceForm);
      ElMessage.success('设备更新成功！');
    } else {
      await deviceStore.addDevice(deviceStore.deviceForm);
      ElMessage.success('设备新增成功！');
    }
    deviceStore.dialogVisible = false;
  } catch (error) {
    if (error === false) { 
      ElMessage.error('表单验证失败，请检查输入项。');
      console.error('Form validation failed:', deviceFormRef.value.fields.filter(field => field.validateState === 'error').map(field => field.validateMessage));
    } else {
      console.error('提交表单失败:', error);
      ElMessage.error(`提交失败: ${error.message || '未知错误'}`);
    }
  } finally {
    deviceStore.formSubmitting = false;
  }
};

const handleCloseDialog = () => {
  deviceStore.dialogVisible = false;
  deviceStore.resetDeviceForm();
  if (deviceFormRef.value) {
    deviceFormRef.value.clearValidate();
  }
};

const handleSelectionChange = (val) => {
  deviceStore.updateSelectedDevices(val);
};

const handleSizeChange = (size) => {
  deviceStore.searchForm.pageSize = size;
  deviceStore.searchForm.pageNo = 1;
  deviceStore.fetchDeviceList();
};

const handleCurrentChange = (page) => {
  deviceStore.searchForm.pageNo = page;
  deviceStore.fetchDeviceList();
};

const handleViewDetail = (row) => {
  const detailHtml = `
    <div style="max-height: 400px; overflow-y: auto; padding-right: 10px;">
      <p><strong>设备ID:</strong> ${row.eqid || 'N/A'}</p>
      <p><strong>设备名称:</strong> ${row.eqname || 'N/A'}</p>
      <p><strong>设备类型:</strong> ${row.eqtype || 'N/A'}</p>
      <p><strong>设备状态:</strong> <span class="el-tag el-tag--${getStatusTagType(row.eqstatus)}">${getDeviceStatusLabel(row.eqstatus)}</span></p>
      <p><strong>设备型号:</strong> ${row.eqmodel || 'N/A'}</p>
      <p><strong>制造商:</strong> ${row.eqmanufacture || 'N/A'}</p>
      <p><strong>购买日期:</strong> ${row.eqtime ? row.eqtime.split('T')[0] : 'N/A'}</p>
      <p><strong>数量:</strong> ${row.eqcount || 'N/A'}</p>
      <p><strong>价格:</strong> ${row.eqprice ? row.eqprice + ' 元' : 'N/A'}</p>
      <p><strong>电压:</strong> ${row.eqv ? row.eqv + ' V' : 'N/A'}</p>
      <p><strong>电流:</strong> ${row.eqa ? row.eqa + ' A' : 'N/A'}</p>
      <p><strong>功率:</strong> ${row.eqw ? row.eqw + ' W' : 'N/A'}</p>
      <p><strong>设备描述:</strong> ${row.eqdiscribe || '无'}</p>
    </div>
  `;
  ElMessageBox.alert(detailHtml, '设备详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    callback: () => {}
  });
};

onMounted(() => {
  deviceStore.fetchDeviceList();
});
</script>

<style scoped>
.device-list-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 18px;
}

.table-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
}

.table-header .el-button {
  margin-right: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
